package com.xijia8.strategy.strategy;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xijia8.strategy.entity.AdminStrategy;
import com.xijia8.strategy.mapper.AdminStrategyMapper;
import com.xijia8.strategy.utils.SpringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 策略
 */
@Component
public class StrategyContext {

    @Autowired
    private AdminStrategyMapper strategyMapper;

    /**
     * 通过策略Id 寻找容器Id
     * @param strategyId
     * @param strategyType
     * @param t
     * @param <T>
     * @return
     */
    public <T> T getStrategy(String strategyId, Integer strategyType, Class<T> t) {
        // strategyId bean id 验证参数
        if (StringUtils.isEmpty(strategyId)) {
            return null;
        }
        if (strategyType == null) {
            return null;
        }
        if (t == null) {
            return null;
        }
        // 根据策略id查询 (策略id不能重复)
        AdminStrategy strategy = strategyMapper.selectOne(new LambdaQueryWrapper<AdminStrategy>()
                .eq(AdminStrategy::getStrategyId, strategyId)
                .eq(AdminStrategy::getStrategyType, strategyType)
                .eq(AdminStrategy::getDisable, 0)
        );
        if (strategy == null) {
            return null;
        }
        String strategyBeanId = strategy.getStrategyBeanId();
        if (StringUtils.isEmpty(strategyBeanId)) {
            return null;
        }
        T bean = SpringUtils.getBean(strategyBeanId, t);
        return bean;
    }
}
